package com.itheima.controller.store;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.controller.BaseServlet;
import com.itheima.service.impl.store.PieServiceImpl;
import com.itheima.service.store.PieService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@WebServlet("/store/piechart/*")
public class PieServlet extends BaseServlet {
    PieService pieService = new PieServiceImpl();


    protected void pie(HttpServletRequest req, HttpServletResponse resp) {

        List<Map<String, Object>> list = pieService.findSexCount();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("sexCount",list);

        List<String> sexNames = new ArrayList<String>();
        for(Map<String,Object> m : list){
            String sex = (String) m.get("sex");
            sexNames.add(sex);
        }
        map.put("sex",sexNames);

        try {
            String json=new ObjectMapper().writeValueAsString(map);
            resp.setContentType("text/json;charset=utf-8");
            resp.getWriter().write(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getpie(HttpServletRequest req, HttpServletResponse resp){
        try {
            req.getRequestDispatcher("/WEB-INF/pages/store/piechart/pie.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
